package com.zsr.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.example.entity.EduComment;
import com.zsr.example.entity.UcenterMember;
import com.zsr.example.mapper.EduCommentMapper;
import com.zsr.example.service.EduCommentService;
import com.zsr.example.service.UcenterMemberService;
import com.zsr.example.util.SensitiveWordFilter;
import com.zsr.example.util.constants.CommentConstants;
import com.zsr.example.util.constants.SysConstants;
import com.zsr.example.vo.CommentReq;
import com.zsr.example.vo.CommentVo;
import com.zsr.example.vo.front.EduCommentVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-12-04
 */
@Service
@Slf4j
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {
    @Autowired
    private UcenterMemberService ucenterMemberService;
    @Autowired
    private SensitiveWordFilter sensitiveWordFilter;


    @Override
    public Map<String, Object> commentPageList(Long page, Long limit, int targetType, String targetId) {

        //long begin = System.currentTimeMillis();
        Page<EduComment> pageParam = new Page<>(page, limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id", targetId);
        wrapper.eq("target_type", targetType);// 1 course ,2 vod ,3 article
        wrapper.eq("root_id", 0);
        wrapper.orderByDesc("gmt_create");

        this.page(pageParam, wrapper);
        List<EduComment> commentList = pageParam.getRecords();
        QueryWrapper<EduComment> replyWrapper = new QueryWrapper<>();
        wrapper.eq("target_id", targetId);
        wrapper.eq("target_type", targetType);// 1 course ,2 vod ,3 article
        wrapper.ne("root_id", 0);
        List<EduComment> replyList = this.list(replyWrapper);
        List<EduCommentVo> result = new ArrayList<>();

        //list 转map
        Map<String, UcenterMember> maps = ucenterMemberService.list(null).stream().collect(Collectors.toMap(UcenterMember::getId, Function.identity()));

        //一级评论列表
        //todo 性能优化
        for (int i = 0; i < commentList.size(); i++) {
            if (commentList.get(i).getRootId().equals("0")) {
                EduCommentVo commentVo = new EduCommentVo();
                BeanUtils.copyProperties(commentList.get(i), commentVo);
                //获取头像昵称
                commentVo.setFromNickname(maps.get(commentVo.getFromMemberId()).getNickname());
                commentVo.setFromAvatar(maps.get(commentVo.getFromMemberId()).getAvatar());
                //peek接收一个Consumer 没有返回值的，而map接收一个Function 有返回值的。
                commentVo.setReply(replyList.stream().filter(x -> x.getRootId().equals(commentVo.getId()))
                        .peek(x -> ComPeekConsumer(x, maps)).collect(Collectors.toList()));
                result.add(commentVo);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("items", result);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());

        /*long end = System.currentTimeMillis();
        System.out.println(end - begin);*/
        return map;
    }

    @Override
    public UcenterMember commentSave(EduComment comment, String memberId) {
        //敏感词过滤
        if(comment.getType()!=CommentConstants.TYPE_COM && !memberId.equals(comment.getToMemberId())){
            comment.setStatus(SysConstants.STATUS_NO_READ);//未读状态
        }
        Set<String> set = sensitiveWordFilter.getSensitiveWord(comment.getContent(), 1);
        if (set.size() > 0) log.debug("用户:{} 语句中包含敏感词的个数为：{}。包含{}", memberId, set.size(), set);
        comment.setContent(sensitiveWordFilter.replaceSensitiveWord(comment.getContent(), 1, 1));

        //TODO 考虑不写入昵称和头像 连表查询
        UcenterMember user = ucenterMemberService.getById(memberId);
        comment.setFromNickname(user.getNickname());
        comment.setFromAvatar(user.getAvatar());
        comment.setFromMemberId(memberId);


        this.save(comment);
        return user;
    }

    private void ComPeekConsumer(EduComment x, Map<String, UcenterMember> maps) {
        UcenterMember from = maps.get(x.getFromMemberId());
        UcenterMember to = maps.get(x.getToMemberId());
        x.setFromNickname(ObjectUtils.isEmpty(from) ? "用户已注销" : from.getNickname());
        x.setFromAvatar(ObjectUtils.isEmpty(from) ? "" : from.getAvatar());
        if(ObjectUtils.isNotEmpty(to))x.setToNickname(to.getNickname());
    }

    /**
     * 获取我的评论消息
     * @param uId
     * @return
     */
    public List<EduComment> getMyReplyMsg(String uId){
        return baseMapper.getMyReplyMsg(uId);
    }



    @Override
    public List<CommentVo> getListByTargetId(CommentReq commentReq) {
        return  baseMapper.getCommentList(commentReq);
    }

}
